// TodoService.java
package com.mytools.project.todo.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mytools.project.todo.entity.Todo;
import com.mytools.project.todo.mapper.ToDoPlusMapper;
import com.mytools.project.todo.req.TodoReq;
import com.mytools.project.todo.resp.TodoAllResp;
import com.mytools.project.todo.resp.TodoTaskOutResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TodoService {
    
//    @Autowired
//    private TodoMapper todoMapper;

    @Autowired
    private ToDoPlusMapper tdMapper;
    
//    public List<Todo> getTodosByUserId(String userId) {
//        return todoMapper.selectByUserId(userId);
//    }
    
    public Todo getTodoById(Long id) {
        return tdMapper.selectById(id);
    }
    
    public int createTodo(Todo todo) {
        todo.setCreatedAt(LocalDateTime.now());
        todo.setUpdatedAt(LocalDateTime.now());
        todo.setCompleted(false);
        return tdMapper.insert(todo);
    }
    
    public int updateTodo(Todo todo) {
        return tdMapper.updateById(todo);
    }
    
    public int deleteTodo(Long id) {
        return tdMapper.deleteById(id);
    }

    public TodoTaskOutResp getStatisticsTask(String userId) {
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1);
        Map<String, Object> stats = new HashMap<>();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Todo> todos = tdMapper.selectList(queryWrapper);


        // 使用分区和分组进行一次性处理
        java.util.Map<LocalDate, List<Todo>> todosByDate = todos.stream()
                .collect(Collectors.groupingBy(Todo::getDueDate));

        List<Todo> todayTodos = todosByDate.getOrDefault(today, List.of());
        List<Todo> tomorrowTodos = todosByDate.getOrDefault(tomorrow, List.of());

        // 过期任务
        List<Todo> overdueTodos = todos.stream()
                .filter(todo -> todo.getDueDate().isBefore(today))
                .filter(todo -> !Boolean.TRUE.equals(todo.getCompleted()))
                .collect(Collectors.toList());

        TodoTaskOutResp resp = new TodoTaskOutResp();

        // 处理今日任务
        resp.setTodayTask(todayTodos.stream()
                .filter(todo -> !Boolean.TRUE.equals(todo.getCompleted()))
                .map(Todo::getTitle)
                .collect(Collectors.toList()));

        resp.setTodayCompleteTaskCount((int) todayTodos.stream()
                .filter(todo -> Boolean.TRUE.equals(todo.getCompleted()))
                .count());

        resp.setTodayAllTaskCount(todayTodos.size());

        // 处理明日任务
        resp.setTomorrowTask(tomorrowTodos.stream()
                .filter(todo -> !Boolean.TRUE.equals(todo.getCompleted()))
                .map(Todo::getTitle)
                .collect(Collectors.toList()));

        resp.setTomorrowTaskCount(tomorrowTodos.size());

        // 处理过期任务
        resp.setOverDueTask(overdueTodos.stream()
                .map(Todo::getTitle)
                .collect(Collectors.toList()));

        resp.setOverDueTaskCount(overdueTodos.size());

        resp.setUrl("http://mytools.yutang1314.fun:9000/"); // 您可以根据需要设置URL

        return resp;
    }
    
    public TodoAllResp getStatistics(String userId) {
        Map<String, Object> stats = new HashMap<>();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Todo> todos = tdMapper.selectList(queryWrapper);
        int total = todos.size();
        int completed = complete(userId,false).size();
        int overdue = overdue(userId).size();
        int today = todayTodo(userId).size();
        
        double completionRate = total > 0 ? (double) completed / total * 100 : 0;
        TodoAllResp todoAllResp = new TodoAllResp();
        todoAllResp.setUserId(userId);
        todoAllResp.setTotal(String.valueOf(total));
        todoAllResp.setToday(String.valueOf(today));
        todoAllResp.setOverdue(String.valueOf(overdue));
        todoAllResp.setCompleted(String.valueOf(completed));
        todoAllResp.setCompletionRate(String.valueOf(completionRate));
//        stats.put("total", total);
//        stats.put("completed", completed);
//        stats.put("overdue", overdue);
//        stats.put("today", today);
//        stats.put("completionRate", Math.round(completionRate * 100.0) / 100.0);
        
        return todoAllResp;
    }

    /**
     * 统计所有待办数据
     * @param userId
     * @return
     */
    public List<Todo> allTodoData(String userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Todo> completeData = tdMapper.selectList(queryWrapper);

        // 定义优先级映射，用于比较
        Map<String, Integer> priorityOrder = new HashMap<>();
        priorityOrder.put("high", 0);
        priorityOrder.put("medium", 1);
        priorityOrder.put("low", 2);

        // 按照优先级和截止日期排序
        completeData.sort(Comparator
                .comparing((Todo todo) -> priorityOrder.getOrDefault(todo.getPriority(), 3))
                .thenComparing(Todo::getDueDate)
                .thenComparing(Todo::getCreatedAt, Comparator.reverseOrder()));

        return CollectionUtil.defaultIfEmpty(completeData, new ArrayList<>());
    }


    /**
     * 统计当日待办
     * @param userId
     * @return
     */
    public List<Todo> todayTodo(String userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("completed", false);
        queryWrapper.apply("DATE(due_date) = CURDATE()");
        List completeData = tdMapper.selectList(queryWrapper);
        return CollectionUtil.defaultIfEmpty(completeData, new ArrayList<>());
    }

    /**
     * 统计所有超时的待办
     * @param userId
     * @return
     */
    public List<Todo> overdue(String userId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("completed", false);
        queryWrapper.apply("due_date < CURDATE()");
        List completeData = tdMapper.selectList(queryWrapper);
        return CollectionUtil.defaultIfEmpty(completeData, new ArrayList<>());
    }

    /**
     * 统计所有已完成的待办
     * @param userId
     * @return
     */
    public List<Todo> complete(String userId,Boolean today) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("completed", true);
        if(today){
            queryWrapper.apply("DATE(completed_at) = CURDATE()");
        }
        List completeData = tdMapper.selectList(queryWrapper);
        return completeData;
    }


    public int updateTodoComplete(TodoReq todoReq) {
        Todo todo = new Todo();
        BeanUtil.copyProperties(todoReq,todo);
        todo.setCompletedAt(todoReq.getCompleted() ? LocalDateTime.now() : null);
        return tdMapper.updateById(todo);
    }
}